<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>分类参数</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图 -->
    <el-card>
      <el-alert :closable="false" :show-icon="true" title="注意：只允许为第三级分类设置相关参数！" type="warning"></el-alert>
      <el-row class="cat_opt">
        <el-col>
          <span>选择商品分类 : &nbsp;&nbsp;&nbsp;&nbsp;</span>
          <el-cascader
            expand-trigger="hover"
            :options="cateList"
            :props="cascaderProps"
            v-model="selectedKeys"
            @change="handleChange"
          ></el-cascader>
        </el-col>
      </el-row>

      <el-tabs v-model="activeName" @tab-click="handleClick">
        <!-- 动态参数 -->
        <el-tab-pane label="动态参数" name="many">
          <el-button
            type="primary"
            size="mini"
            :disabled="isBtnDisabled"
            @click="addDialogVisible = true"
          >添加参数</el-button>
          <el-table :data="paramList">
            <el-table-column type="expand">
              <template slot-scope="scope">
                <!-- 循环渲染Tag标签 -->
                <el-tag
                  v-for="(item, i) in scope.row.attr_vals"
                  :key="i"
                  closable
                  @close="handleClose(i, scope.row)"
                >{{item}}</el-tag>

                <!-- 添加按钮 -->

                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputComfirm(scope.row)"
                  @blur="handleInputComfirm(scope.row)"
                ></el-input>
                <!-- 添加按钮 -->
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                >+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column type="index"></el-table-column>
            <el-table-column prop="attr_name" label="参数名称"></el-table-column>
            <el-table-column prop="address" label="操作">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="primary"
                  icon="el-icon-edit"
                  @click="showEditDialog(scope.row)"
                >编辑</el-button>
                <el-button size="mini" type="danger" icon="el-icon-delete">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>

        <!-- 静态属性 -->
        <el-tab-pane label="静态属性" name="only">
          <el-button
            type="primary"
            size="mini"
            :disabled="isBtnDisabled"
            @click="addDialogVisible = true"
          >添加属性</el-button>
          <el-table :data="paramList">
            <el-table-column type="expand">
              <template slot-scope="scope">
                <!-- 循环渲染Tag标签 -->
                <el-tag v-for="(item, i) in scope.row.attr_vals" :key="i" closable>{{item}}</el-tag>

                
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputComfirm(scope.row)"
                  @blur="handleInputComfirm(scope.row)"
                ></el-input>
                <!-- 添加按钮 -->
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                >+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column type="index"></el-table-column>
            <el-table-column prop="attr_name" label="参数名称"></el-table-column>
            <el-table-column prop="address" label="操作">
              <el-button
                size="mini"
                type="primary"
                icon="el-icon-edit"
                @click="showEditDialog(scope.row)"
              >编辑</el-button>
              <el-button size="mini" type="danger" icon="el-icon-delete">删除</el-button>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <!-- 添加参数的对话框 -->
    <el-dialog
      :title="'添加'+ titleText"
      :visible.sync="addDialogVisible"
      width="50%"
      @close="addDialogClosed"
    >
      <!-- 添加参数的对话框 -->
      <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="100px">
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="addForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addParams">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改参数的对话框 -->
    <el-dialog
      :title="'添加'+ titleText"
      :visible.sync="editDialogVisible"
      width="50%"
      @close="editDialogClosed"
    >
      <!-- 添加参数的对话框 -->
      <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="100px">
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="editForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editParams">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      cateList: [],
      cascaderProps: {
        value: "cat_id",
        label: "cat_name",
        children: "children"
      },
      activeName: "many",
      selectedKeys: [],
      //   monylist onlylist
      paramList: [],
      addDialogVisible: false,
      addForm: {
        attr_name: ""
      },
      addFormRules: {
        attr_name: [{ required: true, message: "不能为空", trigger: "blur" }]
      },
      editForm: {
        attr_name: ""
      },
      editDialogVisible: false,
      editFormRules: {
        attr_name: [{ required: true, message: "不能为空", trigger: "blur" }]
      }
    };
  },
  created() {
    this.getCateList();
  },
  methods: {
    // 获取商品分类数据
    async getCateList() {
      const { data: res } = await this.$http.get("categories");

      if (res.meta.status !== 200) {
        return this.$message.error("获取商品分类失败！");
      }
      // 把数据列表，赋值给 cateList
      this.cateList = res.data;
    },
    handleChange() {
      this.queryParamsList();
    },
    handleClick() {
      console.log(this.activeName);
      this.queryParamsList();
    },
    async queryParamsList() {
      // 如果这个数组的长度 小于 3 则重置
      // 现在选择范围 只能选择三级分类
      if (this.selectedKeys.length != 3) {
        this.paramList = []
        return (this.selectedKeys = []);
      }
      // 获取数据
      const { data: res } = await this.$http.get(
        `categories/${
          this.selectedKeys[this.selectedKeys.length - 1]
        }/attributes`,
        { params: { sel: this.activeName } }
      );
      // this.paramList = res.data;
      // this.paramList.forEach(item => {
      //   if (item.attr_vals == "") {
      //     item.attr_vals = [];
      //   } else {
      //     item.attr_vals = item.attr_vals.split(" ");
      //   }
      //   item.inputVisible = false;
      //   // 文本框中输入的值
      //   item.inputValue = "";
      // });

      res.data.forEach(item => {
        if (item.attr_vals == "") {
          item.attr_vals = [];
        } else {
          item.attr_vals = item.attr_vals.split(" ");
        }
        item.inputVisible = false;
        // 文本框中输入的值
        item.inputValue = "";
      });
      this.paramList = res.data;
    },
    //当关闭弹窗重置表单数据
    addDialogClosed() {
      // 获取到表单组件的对象
      this.$refs.addFormRef.resetFields();
    },
    addParams() {
      //表单的预校验
      this.$refs.addFormRef.validate(async vali => {
        if (!vali) {
          return this.$message.error("请重新填写正确的内容");
        }
        const { data: res } = await this.$http.post(
          `categories/${this.cateId}/attributes`,
          {
            attr_name: this.addForm.attr_name,
            attr_sel: this.activeName
          }
        );
        if (res.meta.status == 201) {
          this.$message.success("参数添加成功");
          this.queryParamsList();
          this.addDialogVisible = false;
        }
      });
    },
    async editParams() {
      const { data: res } = await this.$http.put(
        `categories/${this.cateId}/attributes/${this.editForm.attr_id}`,
        {
          attr_name: this.editForm.attr_name,
          attr_sel: this.activeName
        }
      );
      if (res.meta.status != 200) {
        return this.$message.error("修改参数失败");
      }
      this.$message.success("修改参数成功");
      this.queryParamsList();
      this.editDialogVisible = false;
    },
    showEditDialog(paramsInfo) {
      // 演示的代码中 是获取 传递过来的参数中id去数据库查询
      // 其实我们可以偷懒 直接拿传递的数据来用

      this.editDialogVisible = true;
      this.editForm = paramsInfo;
      // 待发送修改请求 post请求的参数就来自 editForm
      // 发送修改的请求操作 应该在弹窗中的确定按钮按下时发送
    },
    editDialogClosed() {
      this.editDialogVisible = false;
    },
    showInput(row) {
      row.inputVisible = true;
      // 在修改数据之后立即使用这个方法，获取更新后的 DOM。
      this.$nextTick(() => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },
    async handleInputComfirm(row) {
      // 1 判断 输入的内容 是否合法
      // 是否是空格 是否为空
      if (row.inputValue.trim().length === 0) {
        row.inputVisible = false;
        row.inputValue = "";
        return;
      }
      // 2 如果输入的合法 那么要发送请求 添加一条新的动态参数选项
      row.attr_vals.push(row.inputValue);
      row.inputVisible = false;
      row.inputValue = "";
      this.updateAttr(row)
    },
    handleClose(i, row) {
      // 根据当前要删除的数据索引 到数组中删除某个成员
      row.attr_vals.splice(i, 1);
      // 向服务器发送请求 更新参数的选项
      this.updateAttr(row)
    },
    async updateAttr(row) {
      var { data: res } = await this.$http.put(
        `categories/${this.cateId}/attributes/${row.attr_id}`,
        {
          attr_name: row.attr_name,
          attr_sel: row.attr_sel,
          attr_vals: row.attr_vals.join(" ")
        }
      );
      if (res.meta.status == 200) {
        this.$message.success("成功");
        this.queryParamsList();
      }else{
        this.$message.error("失败");
      }
    }
  },
  computed: {
    isBtnDisabled: function() {
      if (this.selectedKeys.length != 3) {
        return true;
      } else {
        return false;
      }
    },
    titleText() {
      if (this.activeName == "many") {
        return "动态参数";
      } else {
        return "静态属性";
      }
    },
    cateId() {
      //获取id的值
      return this.selectedKeys[this.selectedKeys.length - 1];
    }
  }
};
</script>

<style lang="less" scoped>
.cat_opt {
  margin-top: 15px;
}
.el-tag {
  margin-right: 10px;
}
.input-new-tag {
  width: 120px;
}
</style>